package com.easyfun.healthmagicbox.bluetooth;

import java.util.Arrays;

import android.util.Log;



public abstract class MessageParser<T> {	

	private static final String TAG = MessageParser.class.getSimpleName();
	protected byte[] innerBuffer = new byte[1024];
	protected int innerLen = 0;
	public abstract T parse(byte[] buffer1,int len) ;
	
	protected abstract byte[] getIntegratedMessage();

	protected int compareTo(byte[] buffer1, int offset1, int length1,
			byte[] buffer2, int offset2, int length2) {
		// Short circuit equal case
		if (buffer1 == buffer2 && offset1 == offset2
			&& length1 == length2) {
			return 0;
		}
		// Bring WritableComparator code local
		int end1 = offset1 + length1;
		int end2 = offset2 + length2;
		for (int i = offset1, j = offset2; i < end1 && j < end2; i++, j++) {
			int a = (buffer1[i] & 0xff);
			int b = (buffer2[j] & 0xff);
			if (a != b) {
				return a - b;
			}
		}
		return length1 - length2;
	}
	
	protected byte[] rearrangeBuffer(int begin, int end )
	{
		int msgLen = end - begin;
		byte[] tmp = new byte[msgLen];
		

		System.arraycopy(innerBuffer, begin, tmp, 0, msgLen);
//      for (int i = 0; i < eatBuffer; i++) {
//    	buffer[lenbuffer - eatBuffer + i] = 0;						
//	}

		int leftlen = innerLen - end;
		//remove the integrateMsg from innerBuffer
		System.arraycopy(innerBuffer, end, innerBuffer, 0, leftlen);
		//fill 0 after left bytes
		Arrays.fill(innerBuffer,leftlen,innerBuffer.length,(byte)0);
		
		innerLen = leftlen;
		Log.i(TAG, "innerLen: " + innerLen + " innerBuffer:" + printHexString(innerBuffer));
		return tmp;
	}
	
	public static String printHexString( byte[] b) { 
		int len = b.length>50?50:b.length;
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < len; i++) { 
			String hex = Integer.toHexString(b[i] & 0xFF); 
			if (hex.length() == 1) { 
				hex = '0' + hex + " "; 
			} 
			result.append(hex.toUpperCase() ); 
		} 
		return result.toString();
	} 
}
